package com.gitee.fsmxm.wt.ws;

import com.gitee.fsmxm.wt.data.Msg;
import com.gitee.fsmxm.wt.data.Users;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * webservice server
 */
@ServerEndpoint("/chat/{nickname}")
public class ChatServer {

    @OnOpen
    public void onOpen(Session session,
                       @PathParam("nickname") String nickname) throws Exception {
        System.out.println("OnOpen: " + session.getId() + "/" + nickname);

        if (Users.isNicknameLoggedIn(nickname)) {
            session.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, "该昵称已经被使用，请重新登录"));
            return;
        }

        Users.addUser(nickname, session);
        updateOnlineCount();
    }

    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        throwable.printStackTrace();
    }

    private void updateOnlineCount() {
        // 更新在线人数
        Msg msg = new Msg();
        msg.setType("1");
        msg.setContent(String.valueOf(Users.countUser()));
        Gson gson = new Gson();
        String sendMsg = gson.toJson(msg);
        for (Session ses : Users.getSessions()) {
            ses.getAsyncRemote().sendText(sendMsg);
        }
    }

    @OnClose
    public void onClose(Session session,
                        @PathParam("nickname") String nickname) {
        System.out.println("OnClose: " + session.getId() + "/" + nickname);
        if (Users.isSameUser(nickname, session)) {
            Users.removeUser(nickname);
            updateOnlineCount();
        }
    }

    @OnMessage
    public void onMessage(Session session, String msg,
                          @PathParam("nickname") String nickname) {
        System.out.println("OnMessage: " + session.getId() + "/" + nickname + "/" + msg);
        Gson gson = new Gson();
        try {
            Msg message = gson.fromJson(msg, Msg.class);
            message.setNickname(nickname);
            String sendMsg = gson.toJson(message);

            // 用户发送的消息
            if ("0".equals(message.getType())) {
                for (Session ses : Users.getSessions()) {
                    ses.getAsyncRemote().sendText(sendMsg);
                }
            }
        } catch (JsonSyntaxException e) {
            // json语法不对，不做处理（或者此处可关闭websocket连接）
        }

    }

    @OnMessage
    public void onMessage2(Session session, byte[] msg) {
        System.out.println(session.getId() + "/" + new String(msg));
    }

}
